/**
 * 材质调试工具
 * 用于检查场景中材质的透明参数设置
 */

export class MaterialDebugger {
    /**
     * 检查场景中所有材质的透明设置
     * @param {THREE.Scene} scene - Three.js场景对象
     */
    static debugAllMaterials(scene) {
        console.log('\n╔════════════════════════════════════════════════════════════╗');
        console.log('║                    材质透明参数调试报告                    ║');
        console.log('╚════════════════════════════════════════════════════════════╝\n');
        
        const materials = new Map(); // 材质去重
        let meshCount = 0;
        
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                meshCount++;
                const meshMaterials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                meshMaterials.forEach((mat, index) => {
                    const materialKey = `${mat.type}_${mat.uuid}`;
                    
                    if (!materials.has(materialKey)) {
                        const materialInfo = {
                            name: obj.name || '(unnamed)',
                            type: mat.type,
                            uuid: mat.uuid,
                            // 透明相关属性
                            transparent: mat.transparent,
                            alphaTest: mat.alphaTest,
                            depthWrite: mat.depthWrite,
                            depthTest: mat.depthTest,
                            opacity: mat.opacity,
                            // 贴图信息
                            hasMap: !!mat.map,
                            hasAlphaMap: !!mat.alphaMap,
                            // 渲染顺序
                            renderOrder: obj.renderOrder,
                            // 使用该材质的mesh
                            meshes: []
                        };
                        
                        materials.set(materialKey, materialInfo);
                    }
                    
                    // 记录使用该材质的mesh
                    materials.get(materialKey).meshes.push({
                        name: obj.name || '(unnamed)',
                        position: obj.position.clone(),
                        renderOrder: obj.renderOrder
                    });
                });
            }
        });
        
        console.log(`📊 场景统计: ${meshCount} 个Mesh, ${materials.size} 个唯一材质\n`);
        
        // 按类型分组显示
        const transparentMaterials = [];
        const opaqueMaterials = [];
        const problematicMaterials = [];
        const blackTransparentMaterials = [];
        
        for (const [key, info] of materials) {
            const isTransparent = info.transparent || info.alphaTest > 0 || info.opacity < 1;
            
            if (isTransparent) {
                transparentMaterials.push(info);
                
                // 🎯 检查黑色透明材质问题
                const isBlackTransparent = info.name && info.name.toLowerCase().includes('black') || 
                                         info.meshes.some(mesh => mesh.name.toLowerCase().includes('black'));
                
                if (isBlackTransparent) {
                    blackTransparentMaterials.push({
                        ...info,
                        issue: '黑色透明材质可能导致透明区域显示黑色'
                    });
                }
                
                // 检查是否有其他问题
                const isRoadLine = info.meshes.some(mesh => {
                    const name = mesh.name.toLowerCase();
                    return name.includes('road') || name.includes('line') || name.includes('马路') || name.includes('线');
                });
                
                if (isRoadLine && info.transparent && info.depthWrite === false) {
                    problematicMaterials.push({
                        ...info,
                        issue: '马路线材质使用了transparent模式，应该使用alphaTest模式'
                    });
                }
                
                if (!isRoadLine && info.depthWrite === true) {
                    problematicMaterials.push({
                        ...info,
                        issue: '透明材质启用了depthWrite，可能导致渲染问题'
                    });
                }
            } else {
                opaqueMaterials.push(info);
            }
        }
        
        console.log(`━━━ 透明材质 (${transparentMaterials.length}个) ━━━`);
        transparentMaterials.forEach((info, index) => {
            console.log(`${index + 1}. ${info.type} - ${info.name}`);
            console.log(`   透明设置: transparent=${info.transparent}, alphaTest=${info.alphaTest}, opacity=${info.opacity}`);
            console.log(`   深度设置: depthWrite=${info.depthWrite}, depthTest=${info.depthTest}`);
            console.log(`   贴图: map=${info.hasMap}, alphaMap=${info.hasAlphaMap}`);
            console.log(`   使用的Mesh: ${info.meshes.map(m => `${m.name}(renderOrder:${m.renderOrder})`).join(', ')}`);
            console.log('');
        });
        
        console.log(`━━━ 不透明材质 (${opaqueMaterials.length}个) ━━━`);
        opaqueMaterials.slice(0, 5).forEach((info, index) => {
            console.log(`${index + 1}. ${info.type} - ${info.name}`);
            console.log(`   深度设置: depthWrite=${info.depthWrite}, depthTest=${info.depthTest}`);
            console.log('');
        });
        
        if (opaqueMaterials.length > 5) {
            console.log(`   ... 还有 ${opaqueMaterials.length - 5} 个不透明材质未显示\n`);
        }
        
        if (blackTransparentMaterials.length > 0) {
            console.log(`🎨 发现 ${blackTransparentMaterials.length} 个黑色透明材质:`);
            blackTransparentMaterials.forEach((info, index) => {
                console.log(`${index + 1}. ${info.name} - ${info.issue}`);
                console.log(`   建议运行: blackTransparencyFixer.fix() 来修复`);
                console.log('');
            });
        }
        
        if (problematicMaterials.length > 0) {
            console.log(`🔴 发现 ${problematicMaterials.length} 个其他问题材质:`);
            problematicMaterials.forEach((info, index) => {
                console.log(`${index + 1}. ${info.name} - ${info.issue}`);
                console.log(`   当前设置: transparent=${info.transparent}, alphaTest=${info.alphaTest}, depthWrite=${info.depthWrite}`);
                console.log('');
            });
        } 
        
        if (blackTransparentMaterials.length === 0 && problematicMaterials.length === 0) {
            console.log('✅ 未发现材质设置问题！\n');
        }
        
        return {
            total: materials.size,
            transparent: transparentMaterials.length,
            opaque: opaqueMaterials.length,
            problematic: problematicMaterials.length,
            details: Array.from(materials.values())
        };
    }
    
    /**
     * 检查特定材质的设置
     * @param {string} materialName - 材质名称
     */
    static debugMaterialByName(materialName) {
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }
        
        console.log(`🔍 搜索材质: "${materialName}"`);
        
        const foundMeshes = [];
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                materials.forEach((mat) => {
                    if (mat.userData.materialName === materialName || 
                        obj.name.toLowerCase().includes(materialName.toLowerCase())) {
                        foundMeshes.push({
                            meshName: obj.name,
                            material: mat,
                            renderOrder: obj.renderOrder,
                            position: obj.position.clone()
                        });
                    }
                });
            }
        });
        
        if (foundMeshes.length === 0) {
            console.log('❌ 未找到匹配的材质');
            return;
        }
        
        console.log(`✅ 找到 ${foundMeshes.length} 个使用该材质的Mesh:`);
        foundMeshes.forEach((item, index) => {
            const mat = item.material;
            console.log(`${index + 1}. Mesh: ${item.meshName}`);
            console.log(`   材质类型: ${mat.type}`);
            console.log(`   透明设置: transparent=${mat.transparent}, alphaTest=${mat.alphaTest}, opacity=${mat.opacity}`);
            console.log(`   深度设置: depthWrite=${mat.depthWrite}, depthTest=${mat.depthTest}`);
            console.log(`   贴图: map=${!!mat.map}, alphaMap=${!!mat.alphaMap}`);
            console.log(`   渲染顺序: ${item.renderOrder}`);
            console.log(`   位置: (${item.position.x.toFixed(2)}, ${item.position.y.toFixed(2)}, ${item.position.z.toFixed(2)})`);
            console.log('');
        });
    }
}

// 创建便捷实例
const materialDebugger = {
    // 调试所有材质
    debugAll: () => {
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }
        return MaterialDebugger.debugAllMaterials(scene);
    },
    
    // 调试特定材质
    debug: (materialName) => {
        return MaterialDebugger.debugMaterialByName(materialName);
    }
};

// 暴露到全局
window.materialDebugger = materialDebugger;

export default materialDebugger;
